package com.example.springstudyroot.proxy.cglib;

import com.example.springstudyroot.proxy.UserService;
import org.aopalliance.intercept.Interceptor;
import org.springframework.cglib.core.DebuggingClassWriter;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.Factory;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class ProxyTest {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException, InstantiationException, InvocationTargetException {

        //将cglib生成的class文件保存下来
        String dir = "D:\\javaRepository\\myCode\\study\\springstudyroot\\target\\classes";
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, dir);//dir为保存文件路径

        UserService service = new UserService();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(UserService.class);
        enhancer.setCallback(new MethodInterceptor(){
            @Override
            /**
             * Object o,代理对象
             * Method method,当前方法类
             * Object[] objects,传入的方法参数
             * MethodProxy methodProxy,cglib自定义的方法类
             */
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                if (method.getName().equals("eat")) {
                    System.out.println("先洗手");
                   // methodProxy.invoke(o, objects);//proxy
                    method.invoke(service,objects);
                    System.out.println("=========================================");
                    methodProxy.invokeSuper(o,objects);
                    System.out.println("洗碗");
                    return null;
                }
                return method.invoke(service,objects);
            }
        });
        Factory factory = (Factory)enhancer.create();
        UserService userService = (UserService) enhancer.create();
        userService.eat("牛肉");
    }

}
